package com.prince.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.codec.digest.DigestUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @author lhp
 *
 */
public class StringUtil {
	private static String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 过滤空串
	 *
	 * @param str
	 *            字符串
	 * @return 返回结果
	 */
	public static String filterNull(String str) {
		if (str == null) {
			return "";
		} else {
			return str.trim();
		}
	}
	
	/**
	 * 两个字符串不相等
	 * @param source
	 * @param target
	 * @return
	 */
	public static boolean stringNotEquals(String source, String target) {
		return !stringEquals(source, target);
	}

	/**
	 * 两个字符串是否相等
	 *
	 * @param source
	 *            原串
	 * @param target
	 *            目标串
	 * @return 结果
	 */
	public static boolean stringEquals(String source, String target) {
		return isEmpty(source) && isEmpty(target) || !(isEmpty(source) || isEmpty(target)) && source.equals(target);
	}

	public static boolean isEmpty(String str) {
		return filterNull(str).equals("") || null == str || "null".equals(str);
	}

	public static boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}

	/**
	 * 对象是否存在
	 * @param pObj
	 * @return
	 */
	public static boolean isEmpty(Object pObj) {
		if (pObj == null)
			return true;

		if (pObj instanceof String) {
			if (((String) pObj).length() == 0) {
				return true;
			}
		} else if (pObj instanceof Collection) {
			if (((Collection) pObj).size() == 0) {
				return true;
			}
		} else if (pObj instanceof Map) {
			if (((Map) pObj).size() == 0) {
				return true;
			}
		}
		return false;
	}
	
	public static boolean containsAny(String str, String... flag) {
		if (str != null) {
			if (flag == null || flag.length == 0) {
				flag = "[-{-}-]-,".split("-");
			}
			for (String s : flag) {
				if (str.contains(s)) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 是否是 JSON
	 *
	 * @param json
	 *            字符串
	 * @return 返回是否是正确JSON
	 */
	public static boolean isGoodJson(String json) {
		if (isNotEmpty(json)) {
			try {
				JSON.parse(json);
				return true;
			} catch (Exception e) {
				return false;
			}
		} else {
			return false;
		}
	}

	/**
	 * 是否是 对象 JSON
	 *
	 * @param json
	 *            字符串
	 * @return 返回是否是正确JSON
	 */
	public static boolean isGoodObjectJson(String json) {
		if (isNotEmpty(json)) {
			try {
				JSON.parseObject(json);
				return true;
			} catch (Exception e) {
				return false;
			}
		} else {
			return false;
		}
	}

	/**
	 * 是否是 数组 JSON
	 *
	 * @param json
	 *            字符串
	 * @return 返回是否是正确JSON
	 */
	public static boolean isGoodArrayJson(String json) {
		if (isNotEmpty(json)) {
			try {
				JSON.parseArray(json);
				return true;
			} catch (Exception e) {
				return false;
			}
		} else {
			return false;
		}
	}

	public static String[] listToStringArray(List<String> list) {
		if (list != null && !list.isEmpty()) {
			return list.toArray(new String[list.size()]);
		}
		return new String[0];
	}

	public static String[] setToStringArray(Set<String> set) {
		if (set != null && !set.isEmpty()) {
			return set.toArray(new String[set.size()]);
		}
		return new String[0];
	}

	public static List<String> stringsToListArray(String[] strings) {
		if (strings != null && strings.length > 0) {
			return Arrays.asList(strings);
		}
		return new ArrayList<String>();
	}

	public static List<String> stringToListArray(String... strings) {
		if (strings != null && strings.length > 0) {
			return Arrays.asList(strings);
		}
		return new ArrayList<String>();
	}

	public static String getDateByString(Date date, String format) {
		if (StringUtil.isEmpty(format)) {
			format = DEFAULT_FORMAT;
		}
		if (date != null) {
			SimpleDateFormat df = new SimpleDateFormat(format);
			return df.format(date);
		} else {
			return null;
		}
	}

	/**
     * 校验非空参数
     *
     * @Title: checkNotNullParams
     * @Description:
     * @param @param requestParams 待校验参数
     * @param @param set 非空keySet
     * @param @return
     * @return boolean
     * @throws
     */
    public static boolean checkNotNullParams(Map<String, Object> paramMap) {
    	JSONObject requestParams = JSONObject.parseObject
    			(JSON.toJSONString(paramMap));
    	Set<Object> set = new HashSet<Object>();
    	for (Entry<String, Object> m : paramMap.entrySet()) {
    		set.add(m.getKey());
		}
        if (requestParams == null) {
            return false;
        }
        if (set == null || set.size() == 0) {
            return true;
        }
        Set<?> jsonSet = requestParams.keySet();
        if (jsonSet.containsAll(set))
            return true;
        else
            return false;
    }
	
	/**
	 * 浦发银行 12位金额补全
	 * 
	 * @param h
	 * @return
	 */
	public static String completionSPDBTxamt(String h) {
		String s = "";
		int len = 12 - h.length();
		if (len > 0) {
			for (int i = 0; i < len; i++) {
				s += "0";
			}
			s += h;
		}
		return s;
	}

	/**
	 * 浦发银行 12位金额 还原
	 * 
	 * @param h
	 * @return
	 */
	public static String reductionSPDBTxamt(String h) {
		int k = 0;
		for (int i = 0; i < h.length(); i++) {
			if (h.charAt(i) != '0') {
				k = i;
				break;
			}
		}
		h = h.substring(k, h.length());
		return h;
	}

	/**
	 * 反射执行方法
	 * 
	 * @param object
	 *            ,map
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Object reflectMap(Object obj, Map<String, Object> paramMap) {
		try {
			@SuppressWarnings("rawtypes")
			Class objClass = obj.getClass();

			//获取需要模糊查询的字段
			if (MapUtil.isNotEmpty(paramMap,"likeQueryReflect")) {
				String[] likeArry = paramMap.get("likeQueryReflect").toString().split(",");
				
				//循环所需要模糊查询的字段
				for (String like : likeArry) {
					
					//判断是否存在
					if (MapUtil.isNotEmpty(paramMap,like)) {
						
						try {
							//string封装映射
							Method	method = objClass.getMethod("and" + like.toUpperCase().substring(0, 1)
									+ like.substring(1) + "Like",String.class);
							method.invoke(obj,"%"+ paramMap.get(like)+"%");
							
						} catch (Exception e) {
							//int封装映射
							Method	method = objClass.getMethod("and" + like.toUpperCase().substring(0, 1)
									+ like.substring(1) + "Like",Integer.class);
							method.invoke(obj, "%"+ paramMap.get(like)+"%");
							
						}
						
						//移除模糊字段
						paramMap.remove(like);
					}
					
					
				}
				
				//移除模糊字段likeQueryReflect
				paramMap.remove("likeQueryReflect");
				
				
			}
			
			
			//精准查询封装
			for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
				String ss = "and" + entry.getKey().toString().toUpperCase().substring(0, 1)
						+ entry.getKey().toString().substring(1) + "EqualTo";
				System.out.println(ss);

				if (!(null != entry.getValue() && "" != (entry.getValue().toString()))) {
					continue;
				}
				Method method;
				try {
					method = objClass.getMethod("and" + entry.getKey().toString().toUpperCase().substring(0, 1)
							+ entry.getKey().toString().substring(1) + "EqualTo", entry.getValue().getClass());
					method.invoke(obj, entry.getValue());
				} catch (Exception e) {
					method = objClass.getMethod("and" + entry.getKey().toString().toUpperCase().substring(0, 1)
							+ entry.getKey().toString().substring(1) + "EqualTo", Integer.class);

					method.invoke(obj, Integer.parseInt(entry.getValue().toString()));
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return obj;
	}

	/**
	 * MD5签名算法
	 * 
	 * @param res
	 * @return
	 */
	public final static String md5Digest(String res) {
		if (res == null || "".equals(res)) {
			return null;
		}
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		byte[] strTemp;
		try {
			strTemp = res.getBytes("gbk");
		} catch (UnsupportedEncodingException e1) {
			return null;
		}
		try {
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			String dd = new String(str);
			return dd;
		} catch (Exception e) {
			return null;
		}
	}

	public static String getMd5ByFile(File file) {
		String value = null;
		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
			MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(byteBuffer);
			BigInteger bi = new BigInteger(1, md5.digest());
			value = bi.toString(16);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return value;
	}


	
	/**
	 * 将文件转成base64 字符串
	 * 
	 * @param path文件路径
	 * @return *
	 * @throws Exception
	 */

	public static String encodeBase64File(String path) {
		File file = new File(path);
		byte[] buffer = null;
		try {
			FileInputStream inputFile = new FileInputStream(file);
			buffer = new byte[(int) file.length()];

			inputFile.read(buffer);
			inputFile.close();
			// String string = new String(buffer,"iso8859-1");
			// string+="13021339649songchenghong";
			// buffer= string.getBytes("iso8859-1");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Base64.encode(buffer);
	}

	public final static String charsetUtf8(String res) {
		try {
			res = new String(res.getBytes("ISO-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return res;
    }
	
	/**
	 * 获取图片加密串
	 * @param merchantNo
	 * @return
	 */
	public final static String getEncryptData(String merchantNo) {
		String path= null;
		Properties properties = System.getProperties();
		String os = properties.getProperty("os.name");
		if(os.contains("Windows")) {
			path= Thread.currentThread().getContextClassLoader().getResource("").getPath();
			path = path.substring(0,path.indexOf("parent")+7)+"/prince-web/src/main/webapp/md5img/t.png";
			
		}else {
			path="/pub/images/md5img/t.png";
		}
		
        String v = encodeBase64File(path);
    	v = v.replace(" ", "");
    	v = v.replace("/", "");
		Integer start =  (merchantNo.length() / 2 ) * merchantNo.length() * merchantNo.length() / 2 + (merchantNo.length() / 2 ) ;
		Integer end = (merchantNo.length()+merchantNo.length() / 2 ) +merchantNo.length() * ((merchantNo.length() /2 )) * merchantNo.length() / 2 + merchantNo.length() ;
    	v =  v.substring(start, end);
        return v;
	}
	
	
	/**
	 * url 加密
	 * @param url
	 * @param key
	 * @return
	 */
	public static String getKey(String url,String secretKey) {
		if(!url.contains("?")) {
			url = url + "?";
		}
		String urlSign = DigestUtils.md5Hex(url + secretKey).toUpperCase();
		url = url +"&key=" + urlSign;
		return url;
	}

}
